﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1.Utils
{
    internal class StringUtils
    {
        public static byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        public static byte[] hexStringToBytes(String hexString)
        {
            if (hexString != null && !hexString.Equals(""))
            {
                hexString = hexString.ToUpper();
                int length = hexString.Length / 2;
                char[] hexChars = hexString.ToCharArray();
                byte[] d = new byte[length];

                for (int i = 0; i < length; ++i)
                {
                    int pos = i * 2;
                    d[i] = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
                }

                return d;
            }
            else
            {
                return null;
            }
        }
        public static byte charToByte(char c)
        {
            return (byte)"0123456789ABCDEF".IndexOf(c);
        }

        public static String asciiToString(String value)
        {

            StringBuilder sbu = new StringBuilder();

            for (int i = 0; i < value.Length; i++)
            {
                //System.out.println("chars[i]="+chars[i]);
                String s = String.Format("{0:x2}", (byte)value[i]);
                sbu.Append(s);
            }
            return sbu.ToString();
        }

        public static byte[] stringToAsciiArr(String value)
        {
            return System.Text.Encoding.Default.GetBytes(value);
        }
    }
}
